#include <my_head.h>
#include "cgic.h"
#include "../cgisrc/project.h"

int  msqid;
long name_code;
int  has_recv = 0;

char temp_up_buf[128] = {0};
char temp_low_buf[128] = {0};

char hum_up_buf[128] = {0};
char hum_low_buf[128] = {0};

char illu_up_buf[128] = {0};
char illu_low_buf[128] = {0};

void print_html_info(char *title)
{
    printf("Content-type: text/html;charset=\"UTF-8\"\n\n");//固定格式 必须要加
	printf("<!DOCTYPE html>");
	printf("<html>");
	printf("<body>");
	printf("<center>");
	printf("<h1>%s</h1>", title);//自动跳转
	printf("</center>");
	printf("</body>");
	printf("</html>");
}

// 倒计时结束后回调执行函数
void handler(int argc)
{
	msgrcv(msqid, &msg, sizeof(msg_t) - sizeof(long), name_code, IPC_NOWAIT);
	if (0 == has_recv){
		print_html_info("网络原因导致数据不可达，请稍后重试");
		exit(0);
	}
}

int cgiMain(int argc, const char *argv[]){

    cgiFormString("temp_up", temp_up_buf, sizeof(temp_up_buf));
    cgiFormString("temp_low", temp_low_buf, sizeof(temp_low_buf));

    cgiFormString("hum_up", hum_up_buf, sizeof(hum_up_buf));
    cgiFormString("hum_low", hum_low_buf, sizeof(hum_low_buf));

    cgiFormString("illu_up", illu_up_buf, sizeof(illu_up_buf)); 
    cgiFormString("illu_low", illu_low_buf, sizeof(illu_low_buf));

    /*获取消息队列的key值*/
	key_t my_key = ftok(MSGPATH, 'a');
	if (-1 == my_key){
		return -1;
	}
	/*获取消息队列*/
	msqid = msgget(my_key, IPC_CREAT | 0666);
	if (-1 == msqid){
		return -1;
	}

	/*注册alarm信号*/
	signal(SIGALRM, handler);

	char name[128] = {0};
	memcpy(name, cgiCookie, sizeof(name));
	char *s = name;
	while (*s != '=')
	{
		s++;
	}
	s++;
	strcpy(name, s);

	int i = 0;
	while(name[i]!='\0'){
		name_code += name[i];
		i++;
	}
	
	memset(&msg, 0, sizeof(msg_t));
    strcpy(msg.user.ID, name);
	/*封装消息*/
	msg.msgtype = name_code;
	msg.commd = 2; //设置阈值

    //温度
    if (strlen(temp_up_buf) > 0){
        msg.limitset.tempup = atoi(temp_up_buf);
    }else{
        msg.limitset.tempup = 0;
    }
    if (strlen(temp_low_buf) > 0){
        msg.limitset.tempdown = atoi(temp_low_buf);
    }else{
        msg.limitset.tempdown = 0;
    }
    //湿度
    if (strlen(hum_up_buf) > 0){
        msg.limitset.humeup = atoi(hum_up_buf);
    }else{
        msg.limitset.humeup = 0;
    }
    if (strlen(hum_low_buf) > 0){
        msg.limitset.humedown = atoi(hum_low_buf);
    }else{
        msg.limitset.humedown = 0;
    }
    //光照
    if (strlen(illu_up_buf) > 0){
        msg.limitset.luxup = atoi(illu_up_buf);
    }else{
        msg.limitset.luxup = 0;
    }
    if (strlen(illu_low_buf) > 0){
        msg.limitset.luxdown = atoi(illu_low_buf);
    }else{
        msg.limitset.luxdown = 0;
    }
    
	msgsnd(msqid, &msg, sizeof(msg_t) - sizeof(long), 0);

	alarm(5);

	memset(&msg, 0, sizeof(msg_t));
	msgrcv(msqid, &msg, sizeof(msg_t) - sizeof(long), name_code * 2, 0);
	//获取到了数据
	has_recv = 1;
    print_html_info("设置成功");
   

    return 0;
}